<template>
  <div class="app-container">
    <!-- 左右分栏布局 -->
    <div class="main-layout">
      <!-- 左侧：用能单元结构树 -->
      <div class="left-panel">
        <EnergyUnitTree
          ref="energyUnitTreeRef"
          title="用能单元结构"
          :show-node-actions="false"
          :show-expand-toggle="false"
          :auto-select-first="true"
          @node-click="handleNodeClick"
        />
      </div>

      <!-- 右侧：实时数据展示 -->
      <div class="right-panel">
        <div class="panel-header">
          <h3>实时数据展示</h3>
        </div>

        <!-- 设备标签页 -->
        <div class="device-tabs-container" v-if="deviceList.length > 0">
          <div class="device-tabs">
            <div
              v-for="device in deviceList"
              :key="device.deviceId"
              class="device-tab"
              :class="{ active: selectedDevice?.deviceId === device.deviceId }"
              @click="selectDevice(device)"
            >
              {{ device.groupDeviceName || device.deviceName }}
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="deviceLoading" class="loading-state">
          <el-empty description="正在加载设备数据..." />
        </div>

        <!-- 数据展示区域 -->
        <div class="data-display-container" v-else-if="selectedDevice">
          <!-- 属性加载状态 -->
          <div v-if="propertyLoading" class="property-loading">
            <el-empty description="正在加载设备属性..." />
          </div>

          <!-- 设备属性展示 -->
          <div v-else-if="deviceProperties.length > 0" class="data-sections">
            <!-- 按分组显示属性 -->
            <div
              v-for="group in groupedProperties"
              :key="group.groupName"
              class="data-section"
            >
              <h4 class="section-title">{{ group.groupName }}</h4>
              <div class="data-cards">
                <el-tooltip
                  v-for="item in group.properties"
                  :key="item.key"
                  :content="`点击查看${item.name}历史数据`"
                  placement="top"
                  effect="dark"
                >
                  <div class="data-card" @click="openHistoryModal(item)">
                    <div class="card-header">
                      <div class="card-title-section">
                        <img
                          v-if="item.icon"
                          :src="item.icon"
                          :alt="item.name"
                          class="card-icon"
                        />
                        <img
                          v-else
                          src="/images/defaultIcon.png"
                          :alt="item.name"
                          class="card-icon"
                        />
                        <span class="card-title">{{ item.name }}</span>
                      </div>
                      <span class="card-unit">{{ item.unit }}</span>
                    </div>
                    <div class="card-value">{{ item.value }}</div>
                    <div class="card-time">
                      <el-icon><Clock /></el-icon>
                      {{ item.time }}
                    </div>
                  </div>
                </el-tooltip>
              </div>
            </div>
          </div>

          <!-- 无属性状态 -->
          <div v-else class="empty-properties">
            <el-empty description="该设备暂无数据属性" />
          </div>
        </div>

        <!-- 无数据状态 -->
        <div v-else-if="selectedNode && !deviceLoading" class="empty-state">
          <el-empty description="该用能单元暂无关联设备" />
        </div>
        <div v-else-if="!selectedNode" class="empty-state">
          <el-empty description="请选择用能单元查看关联设备数据" />
        </div>
      </div>
    </div>

    <!-- 历史数据查询弹窗 -->
    <el-dialog
      v-model="historyModalVisible"
      :title="`${selectedProperty?.name}-历史数据查询`"
      width="80%"
      :close-on-click-modal="false"
      class="history-dialog"
    >
      <div class="history-modal-content">
        <!-- 查询条件 -->
        <div class="query-section">
          <div class="query-row">
            <span class="query-label">查询时间：</span>
            <el-date-picker
              v-model="queryDate"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
            />
            <el-button
              type="primary"
              icon="Search"
              @click="searchHistoryData"
              :loading="historyLoading"
              style="margin-left: 12px"
            >
              搜索
            </el-button>
            <el-button
              type="success"
              icon="Download"
              @click="exportHistoryData"
              :loading="exportLoading"
              style="margin-left: 8px"
            >
              导出
            </el-button>
          </div>
        </div>

        <!-- 图表区域 -->
        <div class="chart-section">
          <div
            ref="historyChartRef"
            class="history-chart"
            v-loading="historyLoading"
          ></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from "vue";
import { getDeviceGroupList } from "@/api/deviceManage/energyUnit";
import { getDeviceTypeDetailById } from "@/api/deviceManage/deviceType";
import {
  getDeviceRealtimeData,
  getDeviceHistoryData,
} from "@/api/stat/realtime";
import EnergyUnitTree from "@/components/EnergyUnitTree/index.vue";
import * as echarts from "echarts";

// 基础数据
const selectedNode = ref(null);
const deviceList = ref([]);
const selectedDevice = ref(null);
const searchKeyword = ref("");
const energyUnitTreeRef = ref(null);
const deviceLoading = ref(false);
const deviceProperties = ref([]);
const propertyLoading = ref(false);

// 防重复调用标志
const isLoadingDevices = ref(false);
const isLoadingProperties = ref(false);

// 历史数据弹窗相关
const historyModalVisible = ref(false);
const selectedProperty = ref(null);
const queryDate = ref("");
const historyLoading = ref(false);
const exportLoading = ref(false);
const historyChartRef = ref(null);
const historyChart = ref(null);
const historyData = ref([]);

// 筛选条件
const deviceFilter = reactive({
  meterType: "",
});

// 计算属性：按分组组织属性数据
const groupedProperties = computed(() => {
  if (!deviceProperties.value || deviceProperties.value.length === 0) {
    return [];
  }

  const groups = {};

  deviceProperties.value.forEach((prop) => {
    const groupName = prop.groupName || "其他";
    if (!groups[groupName]) {
      groups[groupName] = {
        groupName: groupName,
        groupCode: prop.groupCode,
        properties: [],
      };
    }
    groups[groupName].properties.push(prop);
  });

  return Object.values(groups);
});

// 用能单元类型选项
const groupTypeOptions = ref([
  { label: "工厂", value: 0 },
  { label: "楼栋", value: 10 },
  { label: "车间", value: 20 },
  { label: "工序", value: 30 },
  { label: "设备", value: 100 },
]);

// 工具函数
function formatTime(timestamp) {
  if (!timestamp) return "--";

  let date;

  // 如果是字符串格式的日期（如 "2025-10-01"）
  if (typeof timestamp === "string") {
    // 如果只有日期没有时间，添加默认时间
    if (timestamp.length === 10) {
      timestamp += " 00:00:00";
    }
    date = new Date(timestamp);
  } else {
    // 如果是数字时间戳
    const ms = timestamp > 1e12 ? timestamp / 1e6 : timestamp;
    date = new Date(ms);
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return "--";
  }

  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
}

// 格式化时间用于图表显示（只显示小时和分钟）
function formatTimeForChart(timestamp, dateStr = null) {
  // 优先使用 dateStr 字段
  if (dateStr) {
    // 解析 dateStr 格式，如 "2025-10-10 10" 或 "2025-10-10 10:30"
    const parts = dateStr.split(" ");
    if (parts.length >= 2) {
      const timePart = parts[1];
      if (timePart.includes(":")) {
        // 如果包含分钟，直接返回
        return timePart;
      } else {
        // 如果只有小时，补全分钟为00
        return `${timePart.padStart(2, "0")}:00`;
      }
    }
  }

  // 如果没有 dateStr 或解析失败，使用时间戳
  if (!timestamp) return "--";

  let date;

  // 如果是字符串格式的日期（如 "2025-10-01"）
  if (typeof timestamp === "string") {
    // 如果只有日期没有时间，添加默认时间
    if (timestamp.length === 10) {
      timestamp += " 00:00:00";
    }
    date = new Date(timestamp);
  } else {
    // 如果是数字时间戳
    const ms = timestamp > 1e12 ? timestamp / 1e6 : timestamp;
    date = new Date(ms);
  }

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    return "--";
  }

  return date.toLocaleString("zh-CN", {
    hour: "2-digit",
    minute: "2-digit",
  });
}

// 树相关函数
function handleNodeClick(data) {
  if (!data || !data.groupName) return;
  selectedNode.value = data;
  loadUnitDevices(data.groupId);
}

function loadUnitDevices(groupId) {
  if (!groupId) {
    deviceList.value = [];
    selectedDevice.value = null;
    return;
  }

  // 防重复调用 - 只有在相同groupId时才跳过
  if (isLoadingDevices.value && selectedNode.value?.groupId === groupId) {
    console.log("相同节点设备列表正在加载中，跳过重复调用");
    return;
  }

  isLoadingDevices.value = true;
  deviceLoading.value = true;

  // 调用真实的设备接口
  getDeviceGroupList(groupId)
    .then((response) => {
      // 过滤掉虚表数据，只显示非虚表的数据
      const allDevices = response.data || [];
      deviceList.value = allDevices.filter((device) => device.isVirtual !== 1);

      // 默认选中第一个设备
      if (deviceList.value.length > 0) {
        selectDevice(deviceList.value[0]);
      }
      deviceLoading.value = false;
      isLoadingDevices.value = false;
    })
    .catch((error) => {
      console.error("获取分组设备失败:", error);
      deviceList.value = [];
      selectedDevice.value = null;
      deviceLoading.value = false;
      isLoadingDevices.value = false;
    });
}

function selectDevice(device) {
  selectedDevice.value = device;
  // 这里可以加载该设备的实时数据
  loadDeviceData(device);
}

function loadDeviceData(device) {
  if (!device || !device.deviceId) {
    deviceProperties.value = [];
    return;
  }

  // 防重复调用 - 只有在相同设备时才跳过
  if (
    isLoadingProperties.value &&
    selectedDevice.value?.deviceId === device.deviceId
  ) {
    console.log("相同设备属性正在加载中，跳过重复调用");
    return;
  }

  isLoadingProperties.value = true;
  propertyLoading.value = true;
  console.log("加载设备实时数据:", device.groupDeviceName || device.deviceName);

  // 调用实时数据接口
  getDeviceRealtimeData(device.deviceId)
    .then((response) => {
      if (response.data) {
        const realtimeData = response.data;

        // 处理数据 - 只处理 proPertyList
        if (realtimeData.proPertyList && realtimeData.proPertyList.length > 0) {
          // 获取 dataDateVo 中的格式化时间
          let latestDateStr = realtimeData.dataDateVo?.dateStr;
          if (!latestDateStr && realtimeData.dataDateVo?.date) {
            // 如果 dateStr 不存在但 date 存在，格式化时间戳
            latestDateStr = formatTime(realtimeData.dataDateVo.date);
          }
          if (!latestDateStr) {
            latestDateStr = "--";
          }
          
          const allProperties = realtimeData.proPertyList.map((prop) => {
            const propValue =
              prop.dataFormCodeValue !== null &&
              prop.dataFormCodeValue !== undefined
                ? prop.dataFormCodeValue
                : null;

            return {
              key: prop.dataCode,
              name: prop.name,
              unit: prop.dataDw || "",
              icon: prop.dataIcon || "/images/defaultIcon.png",
              dataCode: prop.dataCode,
              dataMultiple: prop.dataMultiple || 1,
              groupName: prop.groupName || "其他",
              groupCode: prop.groupCode,
              value:
                propValue !== null
                  ? (propValue * prop.dataMultiple).toFixed(2)
                  : "--",
              time: latestDateStr, // 使用 dataDateVo 中的 dateStr
              rawValue: propValue,
              dataType: prop.dataType,
            };
          });

          deviceProperties.value = allProperties;
        } else {
          deviceProperties.value = [];
        }
      } else {
        deviceProperties.value = [];
      }
      propertyLoading.value = false;
      isLoadingProperties.value = false;
    })
    .catch((error) => {
      console.error("获取设备实时数据失败:", error);
      deviceProperties.value = [];
      propertyLoading.value = false;
      isLoadingProperties.value = false;
    });
}

function searchDevices() {
  // 实现设备搜索逻辑
  console.log("搜索设备:", searchKeyword.value);
}

// 历史数据相关函数
function openHistoryModal(property) {
  selectedProperty.value = property;
  queryDate.value = new Date().toISOString().split("T")[0]; // 默认今天
  historyModalVisible.value = true;

  // 弹窗打开后初始化图表
  nextTick(() => {
    initHistoryChart();
    searchHistoryData();
  });
}

function initHistoryChart() {
  if (!historyChartRef.value) return;

  // 销毁已存在的图表实例
  if (historyChart.value) {
    historyChart.value.dispose();
  }

  historyChart.value = echarts.init(historyChartRef.value);

  // 设置默认配置
  const option = {
    title: {
      text: `${selectedProperty.value?.name}历史数据`,
      left: "center",
      textStyle: {
        fontSize: 16,
        fontWeight: "bold",
        color: "#2c3e50",
      },
    },
    tooltip: {
      trigger: "axis",
      backgroundColor: "rgba(50, 50, 50, 0.9)",
      borderColor: "#4fdaca",
      borderWidth: 1,
      textStyle: {
        color: "#fff",
        fontSize: 12,
      },
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#4fdaca",
        },
      },
      formatter: function (params) {
        if (!params || params.length === 0) return "";
        const data = params[0];
        const unit = selectedProperty.value?.unit || "";
        return `${data.name}<br/>${selectedProperty.value?.name}: ${data.value} ${unit}`;
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: [],
      axisLabel: {
        rotate: 45,
      },
    },
    yAxis: {
      type: "value",
      name: selectedProperty.value?.unit || "",
      nameTextStyle: {
        color: "#666",
      },
    },
    series: [
      {
        name: selectedProperty.value?.name || "",
        type: "line",
        smooth: true,
        symbol: "circle",
        symbolSize: 6,
        showSymbol: true,
        lineStyle: {
          color: "#4fdaca",
          width: 2,
        },
        itemStyle: {
          color: "#4fdaca",
          borderColor: "#fff",
          borderWidth: 2,
        },
        emphasis: {
          scale: true,
          itemStyle: {
            color: "#4fdaca",
            borderColor: "#fff",
            borderWidth: 3,
            shadowBlur: 10,
            shadowColor: "rgba(79, 218, 202, 0.5)",
          },
          lineStyle: {
            width: 3,
          },
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(79, 218, 202, 0.3)",
              },
              {
                offset: 1,
                color: "rgba(79, 218, 202, 0.05)",
              },
            ],
          },
        },
        data: [],
      },
    ],
  };

  historyChart.value.setOption(option);

  // 监听窗口大小变化
  window.addEventListener("resize", () => {
    if (historyChart.value) {
      historyChart.value.resize();
    }
  });
}

function handleDateChange() {
  // 日期变化时自动搜索
  if (queryDate.value) {
    searchHistoryData();
  }
}

function searchHistoryData() {
  if (!selectedProperty.value || !queryDate.value || !selectedDevice.value)
    return;

  historyLoading.value = true;

  // 计算当天的开始和结束时间戳（秒）
  const startOfDay = Math.floor(
    new Date(queryDate.value + " 00:00:00").getTime() / 1000
  );
  const endOfDay = Math.floor(
    new Date(queryDate.value + " 23:59:59").getTime() / 1000
  );

  // 构建API参数
  const params = {
    deviceId: selectedDevice.value.deviceId,
    tag: selectedProperty.value.dataCode,
    start: startOfDay,
    end: endOfDay,
    curPage: 1,
    pagesize: 1000, // 获取足够多的数据点
  };

  // 调用真实的历史数据API
  getDeviceHistoryData(params)
    .then((response) => {
      if (
        response.data &&
        response.data.dataList &&
        response.data.dataList.list &&
        response.data.dataList.list.length > 0
      ) {
        // 处理API返回的数据，先倒序排列（因为第一条是最新时间）
        const processedData = response.data.dataList.list
          .reverse()
          .map((item) => {
            // 从data对象中获取对应的tag值
            const tagValue =
              item.data && item.data[selectedProperty.value.dataCode]
                ? item.data[selectedProperty.value.dataCode]
                : 0;

            return {
              time: formatTimeForChart(item.date, item.dateStr),
              value: parseFloat(tagValue),
            };
          });

        historyData.value = processedData;
        updateHistoryChart(processedData);
      } else {
        // 如果没有数据，显示空状态
        historyData.value = [];
        updateHistoryChart([]);
      }
      historyLoading.value = false;
    })
    .catch((error) => {
      console.error("获取历史数据失败:", error);
      historyData.value = [];
      updateHistoryChart([]);
      historyLoading.value = false;
    });
}

function updateHistoryChart(data) {
  if (!historyChart.value) return;

  if (!data || data.length === 0) {
    // 显示无数据状态
    const option = {
      xAxis: {
        data: [],
      },
      series: [
        {
          data: [],
        },
      ],
      title: {
        text: "暂无历史数据",
        left: "center",
        top: "middle",
        textStyle: {
          color: "#999",
          fontSize: 14,
        },
      },
    };
    historyChart.value.setOption(option);
    return;
  }

  const times = data.map((item) => item.time);
  const values = data.map((item) => item.value);

  const option = {
    xAxis: {
      data: times,
    },
    series: [
      {
        data: values,
      },
    ],
  };

  historyChart.value.setOption(option);
}

function exportHistoryData() {
  if (!historyData.value.length) {
    ElMessage.warning("暂无数据可导出");
    return;
  }

  exportLoading.value = true;

  // 模拟导出
  setTimeout(() => {
    const excelContent = generateExcelContent();
    downloadExcel(
      excelContent,
      `${selectedProperty.value?.name}_${queryDate.value}_历史数据.xlsx`
    );
    exportLoading.value = false;
    ElMessage.success("导出成功");
  }, 1000);
}

function generateExcelContent() {
  // 创建Excel内容
  const headers = ["时间", selectedProperty.value?.name];
  const rows = historyData.value.map((item) => [item.time, item.value]);

  // 简单的Excel格式（CSV格式但扩展名为xlsx）
  const excelContent = [
    headers.join("\t"),
    ...rows.map((row) => row.join("\t")),
  ].join("\n");

  return excelContent;
}

function downloadExcel(content, filename) {
  const blob = new Blob([content], {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8;",
  });
  const link = document.createElement("a");

  if (link.download !== undefined) {
    const url = URL.createObjectURL(blob);
    link.setAttribute("href", url);
    link.setAttribute("download", filename);
    link.style.visibility = "hidden";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }
}

// 主要功能函数

// 页面初始化
onMounted(() => {
  // 树组件会自动加载数据
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background: #f1f2f5;
  height: 100%;
  width: 100%;
  overflow: hidden;
}

// 主布局样式
.main-layout {
  display: flex;
  gap: 20px;
  height: 100%;
  box-sizing: border-box;
}

// 左侧面板样式
.left-panel {
  flex: 0 0 25%;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;

  .panel-header {
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 8px 8px 0 0;

    h3 {
      margin: 0;
      color: #2c3e50;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .tree-container {
    flex: 1;
    padding: 16px;
    overflow: hidden; // 树容器不滚动
  }
}

// 右侧面板样式
.right-panel {
  flex: 1;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: 100%;

  .panel-header {
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 8px 8px 0 0;

    h3 {
      margin: 0;
      color: #2c3e50;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .filter-container {
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
    background: #f8f9fa;

    .filter-row {
      .el-col {
        display: flex;
        align-items: center;
      }
    }
  }

  .device-tabs-container {
    padding: 16px 20px;
    border-bottom: 1px solid #e4e7ed;
    background: #ffffff;

    .device-tabs {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;

      .device-tab {
        padding: 8px 16px;
        background: #f5f5f5;
        border: 1px solid #e4e7ed;
        border-radius: 6px;
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 14px;
        color: #606266;

        &:hover {
          background: #e3f2fd;
          border-color: #4fdaca;
        }

        &.active {
          background: #4fdaca;
          border-color: #4fdaca;
          color: #ffffff;
          box-shadow: 0 2px 8px rgba(79, 218, 202, 0.3);
        }
      }
    }
  }

  .data-display-container {
    flex: 1;
    padding: 20px;
    overflow-y: auto; // 右侧容器可滚动

    .data-sections {
      .data-section {
        margin-bottom: 32px;

        .section-title {
          font-size: 18px;
          font-weight: 600;
          color: #2c3e50;
          margin: 0 0 16px 0;
          padding-bottom: 8px;
          border-bottom: 2px solid #4fdaca;
        }

        .data-cards {
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
          gap: 16px;

          .data-card {
            background: #f8f9fa;
            border: 1px solid #e4e7ed;
            border-radius: 8px;
            padding: 16px;
            transition: all 0.3s ease;

            &:hover {
              background: #e3f2fd;
              border-color: #4fdaca;
              box-shadow: 0 2px 8px rgba(79, 218, 202, 0.15);
              transform: translateY(-2px);
              cursor: pointer;
            }

            .card-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 12px;

              .card-title-section {
                display: flex;
                align-items: center;
                gap: 8px;

                .card-icon {
                  width: 20px;
                  height: 20px;
                  object-fit: contain;
                  border-radius: 4px;
                }

                .card-title {
                  font-size: 14px;
                  color: #606266;
                  font-weight: 500;
                }
              }

              .card-unit {
                font-size: 12px;
                color: #909399;
              }
            }

            .card-value {
              font-size: 24px;
              font-weight: 600;
              color: #2c3e50;
              margin-bottom: 8px;
            }

            .card-time {
              display: flex;
              align-items: center;
              gap: 4px;
              font-size: 12px;
              color: #909399;

              .el-icon {
                font-size: 12px;
              }
            }
          }
        }
      }
    }
  }

  .empty-state {
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px dashed #d9d9d9;
  }

  .loading-state {
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px dashed #d9d9d9;
  }

  .property-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px dashed #d9d9d9;
  }

  .empty-properties {
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px dashed #d9d9d9;
  }
}

// 不同类型标签的颜色样式
.custom-tag {
  &.group-factory {
    background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
    color: #ffffff;
    border: 1px solid #ff5252;
  }

  &.group-building {
    background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
    color: #ffffff;
    border: 1px solid #26a69a;
  }

  &.group-workshop {
    background: linear-gradient(135deg, #45b7d1 0%, #2196f3 100%);
    color: #ffffff;
    border: 1px solid #1976d2;
  }

  &.group-process {
    background: linear-gradient(135deg, #f9ca24 0%, #f0932b 100%);
    color: #ffffff;
    border: 1px solid #ff9800;
  }

  &.group-device {
    background: linear-gradient(135deg, #6c5ce7 0%, #a29bfe 100%);
    color: #ffffff;
    border: 1px solid #9c27b0;
  }
}

// 输入框和选择器样式
:deep(.el-input) {
  .el-input__wrapper {
    border-radius: 6px;

    &:hover {
      border-color: #4fdaca;
    }

    &.is-focus {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}

:deep(.el-select) {
  .el-select__wrapper {
    border-radius: 6px;

    &:hover {
      border-color: #4fdaca;
    }

    &.is-focused {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}

:deep(.el-button) {
  border-radius: 6px;

  &.el-button--primary {
    background: #4fdaca;
    border-color: #4fdaca;

    &:hover {
      background: #32b7cb;
      border-color: #32b7cb;
    }
  }
}

// 历史数据弹窗样式
:deep(.history-dialog) {
  .el-dialog__header {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-bottom: 1px solid #e4e7ed;
    padding: 16px 20px;

    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
      color: #2c3e50;
    }
  }

  .el-dialog__body {
    padding: 0;
  }
}

.history-modal-content {
  .query-section {
    padding: 20px;
    background: #f8f9fa;
    border-bottom: 1px solid #e4e7ed;

    .query-row {
      display: flex;
      align-items: center;
      gap: 12px;

      .query-label {
        font-size: 14px;
        color: #606266;
        font-weight: 500;
        white-space: nowrap;
      }
    }
  }

  .chart-section {
    padding: 20px;

    .history-chart {
      width: 100%;
      height: 500px;
      background: #ffffff;
      border-radius: 8px;
      border: 1px solid #e4e7ed;
    }
  }
}

// 日期选择器样式
:deep(.el-date-editor) {
  .el-input__wrapper {
    border-radius: 6px;

    &:hover {
      border-color: #4fdaca;
    }

    &.is-focus {
      border-color: #4fdaca;
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }
}
</style>
